package vip.ola.pay.channel.yilianpiao;

import com.alibaba.fastjson.JSONObject;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;
import vip.ola.core.common.util.IPUtility;
import vip.ola.core.common.util.MyLog;
import vip.ola.core.entity.PayOrder;
import vip.ola.core.entity.PayPassageAccount;
import vip.ola.pay.channel.yilianpiao.cashierPay.NotifyContent;
import vip.ola.pay.channel.yilianpiao.util.RsaUtils;
import vip.ola.pay.ctrl.common.BaseController;
import vip.ola.pay.mq.BaseNotify4MchPay;
import vip.ola.pay.service.RpcCommonService;
import javax.servlet.http.HttpServletRequest;
import java.io.BufferedReader;
import java.math.BigDecimal;
import java.util.Date;

import static vip.ola.core.common.constant.PayConstant.PAY_STATUS_COMPLETE;
import static vip.ola.core.common.constant.PayConstant.PAY_STATUS_SUCCESS;

@RequestMapping("/api/ylpcash")
@Controller
public class YlpcashPayController extends BaseController {

    private static final MyLog _log = MyLog.getLog(YlpcashPayController.class);

    @Autowired
    private RpcCommonService rpcCommonService;
    @Autowired
    public BaseNotify4MchPay baseNotify4MchPay;

    @RequestMapping("/notify")
    @ResponseBody
    public String notify( HttpServletRequest request){
        _log.info("接收ylpcash回调：" + new Date());
        JSONObject resObj = new JSONObject();
        resObj.put("returnCode","0000");
        // 判断请求IP是否允许+"："
        String clintIp = IPUtility.getClientIp(request);
        _log.info("请求ip为：" + clintIp);
        String sign = request.getHeader("x-efps-sign");
        try{
            BufferedReader br = request.getReader();
            String str = "", wholeStr = "";
            System.out.println("---------------------------------------------------");
            while((str = br.readLine()) != null){
                wholeStr += str;
            }
            if(wholeStr != null && !wholeStr.equals("") && sign != null && !sign.equals("")){
                NotifyContent notify = JSONObject.parseObject(wholeStr, NotifyContent.class);
                String payOrderId = notify.getOutTradeNo();
                PayOrder payOrder = rpcCommonService.rpcPayOrderService.findByPayOrderId(payOrderId);
                Long orderMoney = new BigDecimal(notify.getAmount()).longValue();
                if (orderMoney.longValue() != payOrder.getAmount()){
                    resObj.put("returnMsg","amount not match");
                    return resObj.toJSONString();
                }
                if(payOrder == null){
                    resObj.put("returnMsg","order not exist");
                    return resObj.toJSONString();
                }
                if (payOrder.getStatus() == PAY_STATUS_SUCCESS || payOrder.getStatus() == PAY_STATUS_COMPLETE) {
                    return resObj.toJSONString();
                }
                PayPassageAccount payPassageAccount = rpcCommonService.rpcPayPassageAccountService.findById(payOrder.getPassageAccountId());
                if(payPassageAccount == null || StringUtils.isBlank(payPassageAccount.getParam())){
                    resObj.put("returnMsg","pram is error");
                    return resObj.toJSONString();
                }
                JSONObject accountParams = JSONObject.parseObject(payPassageAccount.getParam());
                String publicKey = accountParams.getString("publicKey");
                boolean result = RsaUtils.vertify(publicKey, wholeStr , sign ) ;
                _log.info("验签结果:" + result);
                if(result){
                    String payState = notify.getPayState();
                    if ("00".equals(payState)){
                        String queryUrl = accountParams.getString("queryUrl");
                        String signNo = accountParams.getString("sign_no");
                        String queryPayState = YlpcashPaymentService.queryDetail(payOrderId,queryUrl,signNo,payPassageAccount.getPassageMchId(),payPassageAccount.getPrivateKey());
                        if ("00".equals(queryPayState)){
                            String channelOrder = notify.getTransactionNo();
                            int result1 = rpcCommonService.rpcPayOrderService.updateStatus4Success(payOrder.getPayOrderId(),channelOrder);
                            _log.info("更新订单状态为支付成功: result={}", result1);
                            if(result1 == 1){
                                // 通知业务系统
                                baseNotify4MchPay.doNotify(payOrder, true);
                                return resObj.toJSONString();
                            }
                        }else {
                            resObj.put("returnMsg","query  is not match");
                        }

                    }else {
                        resObj.put("returnMsg","sign is not match");
                    }
                }else{
                    resObj.put("returnCode", "-1");
                    resObj.put("returnMsg", "inLegal data");
                }
            }else{
                resObj.put("returnCode", "-1");
                resObj.put("returnMsg", "inLegal data");
            }
        }catch (Exception e){
            e.printStackTrace();
            _log.error("YlpcashPayController.notify is error,the message",e.getMessage());
            resObj.put("returnMsg","parase is error");
        }
        return resObj.toJSONString();
    }


    @RequestMapping("/callback")
    @ResponseBody
    public String callback(){
        return "success";
    }
}
